import {Injectable} from "@angular/core";
import {Response} from "@angular/http";
import {API} from "../../../constants/constants";
import {MsgResult} from "../../../models/msg-result";
import {Observable} from "rxjs";
import {Theme} from "./theme";
import {RequestUtil} from "../../../util/request-util";
import {FormUtil} from "../../../util/form-util";

@Injectable()
export class ThemesService {

  constructor(
    private request:RequestUtil,
    private formUtil : FormUtil
  ) { }

  getThemeInfos():Observable<MsgResult>{
    let params = 'isEnable='+'1';
    return this.request.get(API.getThemeInfos,params);
  }


  //修改主题
  updateTheme(theme : Theme):Observable<MsgResult>{
    let params = this.formUtil.serialize(theme);
    return this.request.post(API.updateTheme, params);
  }

  //添加主题
  insertTheme(theme : Theme):Observable<MsgResult>{
    let params = this.formUtil.serialize(theme);
    return this.request.post(API.insertTheme,params);
  }

  //删除主题
  deleteTheme(id : string):Observable<MsgResult>{
    let params="id="+id;
    return this.request.post(API.deleteTheme,params);
  }

  //根据id查询
  getThemeById(id : string):Observable<MsgResult>{
    return this.request.get(API.getThemeById+"&id="+id);
  }



  //返回数据成功
  private success(res: Response) {
   let json = res.json();
   return json as MsgResult;
  }

  //返回数据失败
  private error(error: Response | any) {
    // In a real world app, we might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.log(errMsg);
    return Observable.throw(errMsg);
  }
}
